package org.ocean.online.sys.inner;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.wicket.request.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.ocean.online.utils.RenderUtil;

public class Res {
	String username="";
	Response res;
	String fullFilePath="";
	public Res(Response res,String username){
		this.res = res;
		this.username = username;
	}
	
	public void write(String result){
		getHttpServletResponse().setContentType("text/html");
		getHttpServletResponse().setCharacterEncoding("utf-8");
		try {
			getHttpServletResponse().getOutputStream().write(result.getBytes());
			getHttpServletResponse().flushBuffer();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public void writeStream(InputStream is){
		int size=0;
		try {
			while((size = is.available())>0){
				byte[] buffer = new byte[size];
				is.read(buffer);
				getHttpServletResponse().getOutputStream().write(buffer);	
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void write(String result,String charset){
		getHttpServletResponse().setContentType("text/html");
		getHttpServletResponse().setCharacterEncoding(charset);
		res.write(result.getBytes());
	}
	public void write(byte[] result){
		res.write(result);
	}
	
	public void writeJs(String js){
		String result = "<script type='text/javascript' charset='utf-8'>"+js+"</script>";
		write(result);
	}
	
	public OutputStream getOutputStream(){
		return this.res.getOutputStream();
	}
	
	public HttpServletResponse getHttpServletResponse(){
		HttpServletResponse httpResponse = (HttpServletResponse) res.getContainerResponse();
		return httpResponse;
	}
	
	public void forward(String path){
		String result = "<script type='text/javascript'>window.location='"+path+"'</script>";
		res.write(result.getBytes());
	}
	public void render(String path,JSONObject data){
		File file = new File(fullFilePath);
		String view="";
		try {
			view = RenderUtil.readViewContent(file.getParent()+File.separator+path);
		} catch (FileNotFoundException e) {
			res.write(path+" 404");
			return;
		}
		Document doc = Jsoup.parse(view );
		String hiddenParams = "<span id='pageData' style='display:none'>"+data.toString()+"</span>";
		doc.getElementsByTag("body").append(hiddenParams);
		res.write(doc.html().getBytes());
	}

	@Override
	public String toString() {
		return res.toString();
	}

	public Res setFullFilePath(String fullFilePath) {
		this.fullFilePath = fullFilePath;
		return this;
	}
}
